
#include "XCommon.h"
#include "StdDefs.h"
#include "gameApp.h"
#import "MyView.h"
//#import "Reachability.h"
#import <UIKit/UIKit.h>
#import <CommonCrypto/CommonDigest.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <MessageUI/MFMailComposeViewController.h>

void CWebView::Show(int16 posX,int16 posY,int16 width,int16 height)
{
	if(m_WebView)return;
	
	UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectMake(posX,posY,width,height)];
	[webView setUserInteractionEnabled:YES];//是否支持交互
	//[webView setDelegate:self];//委托
	[webView setOpaque:NO];//透明
	[[(MyView*)CGameApp::GetView() superview] addSubview:webView];
	[webView release];
	m_WebView = webView;
}

void CWebView::Hide()
{
	if(m_WebView)
	{
		[(UIWebView*)m_WebView removeFromSuperview];
		m_WebView= NULL;
	}
}

void CWebView::SetUrl(CXString url)
{
	if(m_WebView)
	{
		[(UIWebView*)m_WebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:(NSString*)url.GetNSString()]]];
	}
}

void CWebView::SetPos(int16 centerX,int16 centerY)
{
	if(m_WebView)
	{
		[(UIWebView*)m_WebView setCenter:CGPointMake(centerX, centerY)];
	}
}

bool CWebView::GoBack()
{
    if([(UIWebView*)m_WebView canGoBack])
    {
        [(UIWebView*)m_WebView goBack];
        return true;
    }
    return false;
}


void CWait::Show(int16 centerX,int16 centerY,int16 width,int16 height)
{
	if(m_WaitControl)return;
	
	UIActivityIndicatorView * indicatorView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
	indicatorView.frame=CGRectMake(centerX - (width>>1), centerY - (height>>1), width, height);
	[[(MyView*)CGameApp::GetView() superview] addSubview:indicatorView];
	[indicatorView startAnimating];
	[indicatorView release];
	m_WaitControl = indicatorView;
}

void CWait::Hide()
{
	if(m_WaitControl)
	{
		UIActivityIndicatorView * indicatorView = (UIActivityIndicatorView*)m_WaitControl;
		[indicatorView stopAnimating];
		[indicatorView removeFromSuperview];
		m_WaitControl = NULL;
	}
}

void CWait::SetPos(int16 centerX,int16 centerY)
{
	if(m_WaitControl)
	{
		UIActivityIndicatorView * indicatorView = (UIActivityIndicatorView*)m_WaitControl;
		[indicatorView setCenter:CGPointMake(centerX, centerY)];
	}
}

CXString Common::GetDeviceMsg( int16 type )
{
	switch (type) 
	{
		case DTYPE_DNAME:
			return [[[UIDevice currentDevice] model] UTF8String];
		case DTYPE_IMEI:
			return [[[UIDevice currentDevice] uniqueIdentifier] UTF8String];
		case DTYPE_SYSVER:
			return [[[UIDevice currentDevice] systemVersion] UTF8String];
		case DTYPE_LANGUAGE:
			return [[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode] UTF8String];
		case DTYPE_APPVER:
			return [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] UTF8String];
		case DTYPE_CARRIER:
		{
			CXString carrierName;
			NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
			if ([currSysVer compare:@"4.0" options:NSNumericSearch] != NSOrderedAscending){
				CTTelephonyNetworkInfo* netInfo=[[CTTelephonyNetworkInfo alloc] init];
				if(netInfo!=nil){
					CTCarrier* carrier=netInfo.subscriberCellularProvider;
					if(carrier!=nil){
						carrierName = [carrier.carrierName UTF8String];
					}
				}
				[netInfo release];
			}
			return carrierName;
		}
		case DTYPE_NETTYPE:
		{
//			Reachability* reach=[Reachability reachabilityForInternetConnection];
//			if(reach!=nil && [reach isReachable]){
//				if([reach isReachableViaWiFi])return "wifi";
//				else if([reach isReachableViaWWAN])return "3G/GPS";
//			}
		}
	}
	return "";
}

void Common::LaunchURL( const char * pName )
{// tel://phonenum http://url 
	NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:pName]];
	[[UIApplication sharedApplication] openURL:url];
}

boolean Common::ReadFile(CXString filename,ResFile& resfile,PathType type)
{
	CXString fullpath = GetSysPath(type) + filename;
	NSData *myData = [[NSData alloc] initWithContentsOfFile:(NSString *)fullpath.GetNSString()];
	
	boolean success = FALSE;
	if( myData )
	{
	    int filesize=[myData length];
		resfile.data = new uint8[filesize];
		resfile.size = filesize;
	    [myData getBytes:resfile.data length:resfile.size];
		success = TRUE;
	}
	[myData release];
	
	return success;
}

boolean Common::WriteFile(CXString filename,ResFile& resfile,PathType type)
{	
	CXString fullpath = GetSysPath(type) + filename;
	NSData * mydata = [NSData dataWithBytesNoCopy:resfile.data length:resfile.size freeWhenDone:NO];
	
	boolean success = FALSE;
	if( mydata != NULL )
	{
		success =  [mydata writeToFile:(NSString *)fullpath.GetNSString() atomically:YES];
		success = TRUE;
	}

	return success;
}

void Common::ShowMsg(CXString title,CXString msg)
{
	UIAlertView* alertView = [[UIAlertView alloc]
							  initWithTitle:(NSString *)title.GetNSString()
							  message:(NSString *)msg.GetNSString()
							  delegate:nil 
							  cancelButtonTitle:@"确定" 
							  otherButtonTitles:nil];
	[alertView show];
	[alertView release];
}

CXString Common::GetSysPath(PathType type)
{
	CXString path;
	if(type==EPATH_APP)
	{
		path.Copy([[[NSBundle mainBundle] resourcePath] UTF8String]);
		path.Append("/");
	}
	else if(type==EPATH_DOC)
	{
		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectory = [paths objectAtIndex:0];
		if( !documentsDirectory )return path;
		path.Copy([[documentsDirectory stringByAppendingPathComponent:@""] UTF8String]);
		path.Append("/");
	}
	else if(type==EPATH_TMP)
	{
		path.Copy([NSTemporaryDirectory() UTF8String]);
	}
	return path;
}

CXString Common::GetFileName(CXString fullpath)
{
	NSString *path = (NSString *)fullpath.GetNSString();
	NSArray *list = [path componentsSeparatedByString:@"/"];
	return [[list objectAtIndex:[list count] - 1] UTF8String];
}

boolean Common::IsFileExist(CXString fullpath)
{
	return [[NSFileManager defaultManager] fileExistsAtPath:(NSString *)fullpath.GetNSString()];
}

boolean Common::PredicateCheck(CXString spcode,CXString checkTxt)
{
	NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",(NSString *)spcode.GetNSString()];
	return [predicate evaluateWithObject:(NSString *)checkTxt.GetNSString()];
}

CXString Common::TimeNow(CXString format)
{
	NSDate* nowDate=[NSDate date];
	NSDateFormatter* dateFormater=[[NSDateFormatter alloc] init];
	[dateFormater setDateFormat:(NSString *)format.GetNSString()];
	CXString timenow = [[dateFormater stringFromDate:nowDate] UTF8String];
	[dateFormater release];
	return timenow;
}

CXString Common::MD5(CXString str) 
{
	const char *cStr = str.Utf8String();
	unsigned char result[CC_MD5_DIGEST_LENGTH];
	
	CC_MD5( cStr, strlen(cStr), result );
	CXString md5code;
	md5code.Format("%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
				   result[0], result[1],
				   result[2], result[3],
				   result[4], result[5],
				   result[6], result[7],
				   result[8], result[9],
				   result[10], result[11],
				   result[12], result[13],
				   result[14], result[15]);
	return md5code;
}

void Common::SendEmail(CXString address,CXString title,CXString body,bool isHtml)
{
	if([MFMailComposeViewController canSendMail])
	{
		MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
		if(picker)
		{
			picker.mailComposeDelegate = ((MyView*)CGameApp::GetView()).m_ViewController;
			NSArray *splist = [(NSString *)address.GetNSString() componentsSeparatedByString:@";"];
			[picker setToRecipients:splist];
			[picker setMessageBody:(NSString *)body.GetNSString() isHTML:isHtml];
			[picker setSubject:(NSString *)title.GetNSString()];
			[((MyView*)CGameApp::GetView()).m_ViewController presentModalViewController:picker animated:YES];
			[picker release];
		}
		else ShowMsg("","请检查邮箱配置");
	}
	else ShowMsg("","请检查邮箱配置");
}

void Common::SavedPhotosAlbum(CXString picpath)
{
	UIImage* uiImage = [[UIImage alloc] initWithContentsOfFile:(NSString*)picpath.GetNSString()];
	UIImageWriteToSavedPhotosAlbum(uiImage,nil,nil,nil);
	[uiImage release];
}

/////////////////////////////////////////////////////////

DataStream::DataStream()
{
}

DataStream::~DataStream()
{
}

void DataStream::SetStream(int8 * buffer,bool isJavaData)
{
	m_iOffset = 0;
	m_pData = buffer;
	m_bIsJavaData = isJavaData;
}

void DataStream::writeByte(int8 data)
{
	m_pData[m_iOffset++]=data;
}

int8 DataStream::readByte()
{
	return m_pData[m_iOffset++];
}

void DataStream::writeShort(int16 data)
{
	if(m_bIsJavaData)
	{
		m_pData[m_iOffset]   = (data & 0xFF00) >> 8;
		m_pData[m_iOffset+1] = (data & 0x00FF);
	}
	else ((int16 *)(&m_pData[m_iOffset]))[0] = data;

	m_iOffset+=2;
}

int16 DataStream::readShort()
{
	int16 ret = -1;
	if(m_bIsJavaData)ret = (m_pData[m_iOffset] << 8) | (m_pData[m_iOffset + 1]);
	else ret = ((int16 *)(&m_pData[m_iOffset]))[0];
	m_iOffset+=2;
	return ret;
}

void DataStream::writeInt(int32 data)
{
	if(m_bIsJavaData)
	{
		m_pData[m_iOffset]   = (data & 0xFF000000) >> 24;
		m_pData[m_iOffset+1] = (data & 0x00FF0000) >> 16;
		m_pData[m_iOffset+2] = (data & 0x0000FF00) >> 8;
		m_pData[m_iOffset+3] = (data & 0x000000FF);
	}
	else ((int32 *)(&m_pData[m_iOffset]))[0] = data;

	m_iOffset+=4;
}

int32 DataStream::readInt()
{
	int32 ret = -1;
	if(m_bIsJavaData)ret = (m_pData[m_iOffset] << 24) | (m_pData[m_iOffset + 1] << 16) | (m_pData[m_iOffset + 2] << 8) | m_pData[m_iOffset + 3];
	else ret = ((int32 *)(&m_pData[m_iOffset]))[0];
	m_iOffset+=4;
	return ret;
}

void DataStream::writeUTF(CXString& data)
{
	const char *pData = data.Utf8String();
	int16 len = strlen(pData);
	writeShort(len);
	MEMCPY(&m_pData[m_iOffset],pData,len);
	m_iOffset += len;
}

void DataStream::readUTF(CXString& data)
{
	int16 len = readShort();
	char * str = new char[len+1];
	MEMSET(str,0,len+1);
	MEMCPY(str,&m_pData[m_iOffset],len);
	data.Copy(str);
	m_iOffset += len;
	delete str;
}

void DataStream::SetOffSet(int32 offset)
{
	m_iOffset = offset;
}

int32 DataStream::GetOffSet()
{
	return m_iOffset;
}


